package com.gzkemays.demo.controller;

import com.gzkemays.demo.service.RedisService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author gzkemays
 * @date 2021/3/18 14:55
 */
@Controller
public class IndexController {
  @Resource RestTemplate restTemplate;
  @Resource RedisService redisService;

  public static final String CLIENT_ID = "gzkemays";
  public static final String CLIENT_SECRET = "gzkemays";
  public static final String GRANT_TYPE = "authorization_code";

  @GetMapping("/index.html")
  public String hello(String code, Model model) {
    if (code != null) {
      // 模拟表单提交，传递 clientId 等信息
      MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
      map.add("code", code);
      map.add("client_id", CLIENT_ID);
      map.add("client_secret", CLIENT_SECRET);
      map.add("grant_type", GRANT_TYPE);
      map.add("redirect_uri", "http://localhost:5002/index.html");
      // 获取该用户的 token
      Map<String, String> resp =
          restTemplate.postForObject("http://localhost:5000/oauth/token", map, Map.class);
      String access_token = "Bearer " + resp.get("access_token");
      System.out.println("获取到的 token：" + access_token);
      // 将 token 存储至 redis
      redisService.saveTokenWithAppId(CLIENT_ID, access_token);
      // 使用 token 访问需要权限的资源
      HttpHeaders headers = new HttpHeaders();
      headers.add("Authorization", access_token);
      HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
      ResponseEntity<String> entity =
          restTemplate.exchange(
              "http://localhost:5001/admin/demo", HttpMethod.GET, httpEntity, String.class);
      model.addAttribute("msg", entity.getBody());
      model.addAttribute("token", access_token);
    }
    return "index";
  }
}
